﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Navigation;
using System.Xml.Linq;
using ProtoType.DataStorage;
using System.IO.IsolatedStorage;
using System.IO;
using System.Windows.Markup;
using System.Collections.ObjectModel;
using ProtoType.ProtoTypeService;

namespace ProtoType
{
    public partial class LayOutControls : PhoneApplicationPage
    {

        #region variable Declaration

        string selectedfid = "";
        string selectedlayouttype = "Simple";
        string bindingid = "";
        DataStructureStore dss;
        ProtoTypeServiceClient client;
        AppSettings apps;

        #endregion

        #region Constructor and Instance creation

        public LayOutControls()
        {
            InitializeComponent();
            dss = new DataStructureStore();
            client = new ProtoTypeServiceClient();
            apps = new AppSettings();
        }

        #endregion

        #region Page events

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (NavigationContext.QueryString.TryGetValue("selectedfid", out selectedfid))
            {
                if (apps.IsolatedStorageSavingSetting)
                {
                    selectedlayouttype = dss.GetSelectedLayOutType(selectedfid);
                    RenderControls(selectedlayouttype);
                    BindData(selectedfid, selectedlayouttype, bindingid, dss.LoadFormList());
                }
                if (apps.WebServiceSavingSetting)
                {
                    client.GetSelectedLayOutTypeAsync(selectedfid);
                    client.GetSelectedLayOutTypeCompleted += new EventHandler<GetSelectedLayOutTypeCompletedEventArgs>(client_GetSelectedLayOutTypeCompleted);
                }

            }

        }

        void client_GetSelectedLayOutTypeCompleted(object sender, GetSelectedLayOutTypeCompletedEventArgs e)
        {
            selectedlayouttype = e.Result.ToString();
            RenderControls(selectedlayouttype);
            if ((Application.Current as App).SelectedFieldBid != null)
            {
                BindDatafromService(selectedfid, selectedlayouttype, (Application.Current as App).SelectedFieldBid);
            }
        }
        void btn_Click(object sender, RoutedEventArgs e)
        {
            Button btn = e.OriginalSource as Button;
            string s = btn.Tag.ToString();
            NavigationService.Navigate(new Uri("/FieldsList.xaml?tag=" + s + "&selectedfid=" + selectedfid, UriKind.Relative));
        }

        private void saveButton_Click(object sender, EventArgs e)
        {
            if (apps.IsolatedStorageSavingSetting)
            {
                SaveDataInIsolatedStorage();
            }
            if (apps.WebServiceSavingSetting)
            {
                SaveDataInService();
            }
        }

        #endregion

        #region Service Events

        private void BindDatafromService(string selectedfid, string selecedlayouttype, string bindingid)
        {
            client.LoadformListAsync();
            client.LoadformListCompleted += new EventHandler<LoadformListCompletedEventArgs>(client_LoadformListCompleted);
        }

        void client_LoadformListCompleted(object sender, LoadformListCompletedEventArgs e)
        {
            BindData(selectedfid, selectedlayouttype, (Application.Current as App).SelectedFieldBid, e.Result.ToObservableCollection());
        }

        void SaveDataInService()
        {
            ProtoTypeServiceClient client1 = new ProtoTypeServiceClient();
            client1.LoadformListAsync(selectedfid);
            client1.LoadformListCompleted += new EventHandler<LoadformListCompletedEventArgs>(client1_LoadformListCompleted);
        }

        void client1_LoadformListCompleted(object sender, LoadformListCompletedEventArgs e)
        {
            string xaml = ReplaceLayoutWithBindingIds(e.Result.ToObservableCollection());
            client.SaveModifiedlayoutAsync(selectedfid, xaml);
            client.SaveModifiedlayoutCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(client_SaveModifiedlayoutCompleted);
        }

        void client_SaveModifiedlayoutCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/FormData.xaml?fid=" + selectedfid, UriKind.Relative));
        }

        #endregion

        #region IsolateStorage events



        void SaveDataInIsolatedStorage()
        {
            ObservableCollection<XElement> formslist = dss.LoadFormList();
            string xaml = ReplaceLayoutWithBindingIds(formslist);
            dss.SaveModifiedLayout(selectedfid, xaml);
            NavigationService.Navigate(new Uri("/FormData.xaml?fid=" + selectedfid, UriKind.Relative));
        }

        #endregion

        #region common Methods

        string ReplaceLayoutWithBindingIds(ObservableCollection<XElement> formslist)
        {
            string xaml = string.Empty;
            Uri uri = new Uri("SampleData/Layout.xml", UriKind.Relative);
            XDocument layoutdoc = XDocument.Load(uri.ToString());

            var layoutdef = from layout in layoutdoc.Descendants("layout") where layout.Attribute("Name").Value == selectedlayouttype select layout;
            foreach (var t in layoutdef)
            {
                if (t.Element("template") != null)
                    xaml = t.Element("template").Element("DataTemplate").ToString();
            }
            if (xaml != string.Empty)
            {

                string myString = xaml;
                List<TextBox> textboxes = new List<TextBox>();
                textboxes = StaticClass.GetTextBoxes(ContentGrid, textboxes);
                int i = 1;
                foreach (XElement ele in formslist.Elements("layout").Elements())
                {

                    string[] Split = myString.Split(new Char[] { '#' });
                    int splicout = Split.Count();
                    foreach (TextBox tb in textboxes)
                    {
                        if (ele.Name.LocalName.ToLower() == tb.Name.ToLower() && (i < Split.Count()))
                        {
                            if (tb.Name.ToLower() != "imagecontrol")
                            {
                                xaml = xaml.Replace("#" + Split.ElementAt(i) + "#", tb.Tag.ToString());
                                i = i + 2;
                            }
                            break;
                        }
                    }
                }
            }
            return xaml;
        }

        void RenderControls(string selecedlayouttype)
        {

            Uri uri = new Uri("SampleData/Layout.xml", UriKind.Relative);
            XDocument Xdoc = XDocument.Load(uri.ToString());

            var template = from temp in Xdoc.Descendants("layout") where temp.Attribute("Name").Value == selecedlayouttype select temp;

            DataTemplates dt = new DataTemplates();
            spcontrol.Children.Clear();

            foreach (XElement t in template.Descendants("control"))
            {

                StackPanel childsp = new StackPanel();

                Button btn = new Button();
                btn.Width = 50;
                btn.Content = "->";
                btn.Tag = t.Value.Replace(" ", "");
                btn.Click += new RoutedEventHandler(btn_Click);

                TextBox tbox = dt.CreateATextBox(t.Value.Replace(" ", ""));
                tbox.IsEnabled = false;
                btn.Width = 100;
                childsp.Children.Add(dt.CreateATextBlock(t.Value));
                childsp.Children.Add(btn);
                childsp.Children.Add(tbox);
                spcontrol.Children.Add(childsp);
            }



        }

        void BindData(string selectedfid, string selecedlayouttype, string bindingid, ObservableCollection<XElement> formslist)
        {
            Uri uri = new Uri("SampleData/Layout.xml", UriKind.Relative);
            XDocument layoutdoc = XDocument.Load(uri.ToString());

            var layoutdef = from layout in layoutdoc.Descendants("layout") where layout.Attribute("Name").Value == selecedlayouttype select layout;

            List<TextBox> textboxes = new List<TextBox>();
            textboxes = StaticClass.GetTextBoxes(ContentGrid, textboxes);


            foreach (XElement t in layoutdef.Descendants("control"))
            {
                foreach (TextBox tb in textboxes)
                {
                    if (tb.Name == t.Value.Replace(" ", ""))
                    {

                        var selectedform = formslist.Where(f => f.Element("id").Value == selectedfid);
                        foreach (XElement ea in selectedform.Elements("layout"))
                        {
                            if (ea.Element(tb.Name) != null)
                            {
                                tb.Text = ea.Element(tb.Name).Element("name").Value;
                                tb.Tag = ea.Element(tb.Name).Element("bid").Value; ;
                                break;
                            }
                        }


                    }

                }
            }

        }

        #endregion
    }
}